package com.ningjingjing.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ningjingjing.util.DBUtil;
import com.ningjingjing.model.Album;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/api/album-list.json")
public class AlbumListApi extends AbsApiServlet {
    @Override
    protected Object doGetInner(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, APIException {
        String keyword = req.getParameter("keyword");
        if (keyword != null && keyword.trim().isEmpty()) {
            keyword = null;
        }

        List<Album> albumList = new ArrayList<>();
        try (Connection c = DBUtil.getConnection()) {
            String sql;

            if (keyword == null) {
                sql = "SELECT aid, name, cover, count FROM album ORDER BY aid DESC";
            } else {
                sql = "SELECT aid, name, cover, count FROM album WHERE name LIKE ? ORDER BY aid DESC";
            }
            try (PreparedStatement s = c.prepareStatement(sql)) {
                if (keyword != null) {
                    s.setString(1, "%" + keyword + "%");
                }
                try (ResultSet rs = s.executeQuery()) {
                    while (rs.next()) {
                        Album album = new Album();
                        album.aid = rs.getInt("aid");
                        album.name = rs.getString("name");
                        album.cover = rs.getString("cover");
                        album.count = rs.getInt("count");

                        albumList.add(album);
                    }
                }
            }
        }

        return albumList;
    }
}
